import React, { useEffect, useRef, useState } from 'react'
import socket from '../../utils/io';
import RealChatItem from '../RealChatItem'
import './index.scss'

interface Idata {
  name?: string
  imgUrl?: string
  message: string
  isSelf?: boolean
  isSystem?: boolean
}



export default function RealChat() {
  const [chatList, setChatList] = useState<Idata[]>([])
  const ref = useRef(null)

  const chatlistChange = (chat: Idata[]) => {
    setChatList(chat);
  }

  useEffect(() => {
    socket.once('send message', function (msg: Idata) {

      const sendNotification = () => {
        const not = new Notification(msg.name!, {
          body: '发来一条消息',
          icon: msg.imgUrl,
        })
        not.onclick = () => {
          not.close()
        }
        setTimeout(() => {
          not.close()
        }, 2000);
      }
      chatlistChange([...chatList, { ...msg, isSelf: msg.name === window.localStorage.getItem('user') }])
      if (document.hidden && !msg.isSystem) {
        if (window.Notification.permission == "granted") { // 判断是否有权限
          sendNotification();
        } else {
          window.Notification.requestPermission(function (permission) { // 没有权限发起请求
            sendNotification();
          });
        }
      }
    });
  }, [chatList])
  useEffect(() => {
    const current = ref.current! as HTMLDialogElement
    current.scrollTop = current.scrollHeight
  }, [chatList])
  return (
    <div className='RealChat' ref={ref}>
      {chatList.map((item, index) => (<RealChatItem data={item} key={index} />))}
    </div>
  )
}
